package edu.hz.pro1_50;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Main1008 {


    private Set<Character> numbers = new HashSet<Character>(Arrays.asList(new Character[]{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}));
    private Set<Character> signs = new HashSet<Character>(Arrays.asList(new Character[]{'+', '-'}));

    public int myAtoi(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }
        str = str.trim();
        if (str.length() == 0) {
            return 0;
        }
        char[] chars = str.toCharArray();
        long value = 0;
        int signValue = 1;
        boolean setSign = false;
        boolean setValue = false;
        for (char ch : chars) {
            if (numbers.contains(ch)) {
                value = value * 10 + signValue * Character.getNumericValue(ch);
                setValue = true;
                if (value < Integer.MIN_VALUE) {
                    return Integer.MIN_VALUE;
                }
                if (value > Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                }
                continue;
            }
            if (signs.contains(ch)) {
                if (setSign && setValue) {
                    break;
                }
                if (setSign && !setValue) {
                    return 0;
                }
                if (setValue) {
                    break;
                }
                if (ch == '-') {
                    signValue = -1;
                }
                setSign = true;
                continue;
            }

            if (!setValue && !setSign) {
                return 0;
            }

            if (setSign && !setValue) {
                return 0;
            }

            if (setSign && setValue) {
                break;
            }
            if (!setSign && setValue) {
                break;
            }
        }
        return new Long(value).intValue();
    }
}
